import { Configuration, App } from '@midwayjs/core';
import * as koa from '@midwayjs/koa';
import * as validate from '@midwayjs/validate';
import * as info from '@midwayjs/info';
import { join } from 'path';
// import { DefaultErrorFilter } from './filter/default.filter';
import { NotFoundFilter } from './filter/notfound.filter';
import { ReportMiddleware } from './middleware/report.middleware';
// import { ProxyMiddleware } from './middleware/proxy.middleware';
import * as cors from '@koa/cors';
import * as multer from '@koa/multer';

@Configuration({
  imports: [
    koa,
    validate,
    {
      component: info,
      enabledEnvironment: ['local'],
    },
  ],
  importConfigs: [join(__dirname, './config')],
})
export class MainConfiguration {
  @App('koa')
  app: koa.Application;

  async onReady() {
    // add middleware
    // ReportMiddleware,
    this.app.useMiddleware([ ReportMiddleware]);
    this.app.use(cors({
      origin: '*',
      allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
      allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
    }));
    
    // 配置文件上传中间件
    const upload = multer({
      storage: multer.memoryStorage(),
      limits: {
        fileSize: 10 * 1024 * 1024, // 10MB
        files: 10 // 最多10个文件
      }
    });
    
    // 为所有路由添加文件上传支持
    this.app.use(async (ctx, next) => {
      if (ctx.headers['content-type']?.includes('multipart/form-data')) {
        // 使用multer处理文件上传，确保能解析所有字段
        await new Promise((resolve, reject) => {
          upload.any()(ctx, next).then(resolve).catch(reject);
        });
        
        // 调试：打印处理后的数据
        console.log('=== Multer处理后的数据 ===');
        console.log('ctx.files:', (ctx as any).files);
        console.log('ctx.body:', (ctx as any).body);
        console.log('ctx.request.body:', ctx.request.body);
      } else {
        await next();
      }
    });
    
    // 确保multer中间件在所有路由之前执行
    this.app.use(async (ctx, next) => {
      // 对于所有请求，如果包含文件上传，确保multer已经处理
      if (ctx.headers['content-type']?.includes('multipart/form-data')) {
        // 如果multer还没有处理过，再次处理
        if (!(ctx as any).files && !(ctx as any).body) {
          console.log('=== 在NotFoundFilter之前重新处理multer ===');
          await new Promise((resolve, reject) => {
            upload.any()(ctx, next).then(resolve).catch(reject);
          });
        }
      }
      await next();
    });
    
    // add filter
    this.app.useFilter([NotFoundFilter]);
    // this.app.useFilter([NotFoundFilter, DefaultErrorFilter]);
  }
}
